package com.db.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoCreateCollection {

	@SuppressWarnings({ "resource" })
	public static void main(String args[]) {
		// 连接到 mongodb 服务
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		// 连接到数据库,如果指定的数据库不存在，mongo会自动创建数据库
		MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
		System.out.println(String.format("Connect to database [%s] successfully", mongoDatabase.getName()));
		
		String table = "user";
		// 判断Collection是否已存在
		boolean has = false;
		for (MongoCursor<String> iterator = mongoDatabase.listCollectionNames().iterator(); iterator.hasNext();) {
			String name = iterator.next();
			if (table.equals(name)) {
				has = true;
				break;
			}
		}
		if (!has) {
			// 创建Collection,即表的概念
			mongoDatabase.createCollection(table);
			System.out.println("create success Collection:" + table);
		}
		// Document相当于行
		MongoCollection<Document> collection = mongoDatabase.getCollection(table);
		System.out.println("create before, size=" + collection.count());
	}
}